package io.renren.modules.sys.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.Query;
import io.renren.modules.sys.dao.BusiBusinessDao;
import io.renren.modules.sys.entity.BusiBusinessEntity;
import io.renren.modules.sys.entity.Constant;
import io.renren.modules.sys.entity.JsonData;
import io.renren.modules.sys.entity.business.Business;
import io.renren.modules.sys.service.BusiBusinessService;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;


@Service("busiBusinessService")
public class BusiBusinessServiceImpl extends ServiceImpl<BusiBusinessDao, BusiBusinessEntity> implements BusiBusinessService {
    private static Logger logger = LoggerFactory.getLogger(BusiBusinessServiceImpl.class);

    @Autowired
    BusiBusinessDao busiBusinessDao;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        Page<BusiBusinessEntity> page = this.selectPage(
                new Query<BusiBusinessEntity>(params).getPage(),
                new EntityWrapper<BusiBusinessEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 获取验证码
     * @param business
     * @return
     */
    @Override
    public JsonData getVerification(Business business) {
        String url = Constant.Business.VerificationURL;
        String param = putParam(business);

        return sendGet(url, param, business);
    }

    /**
     * 订购业务
     * @param business
     * @return
     */
    @Override
    public JsonData order(Business business) {
        String url = Constant.Business.OrderURL;
        String param = putParam(business);

        return sendGet(url, param, business);
    }

    /**
     * 组装参数
     * @param business
     * @return
     */
    private String putParam(Business business) {
        StringBuffer param = new StringBuffer("SPMSCode=" + Constant.Business.VacCode);


        SimpleDateFormat sdf = new SimpleDateFormat("YYYYMMDDHHMMSS");
        String accessTime = sdf.format(new Date());
        param.append("&AccessTime=" + accessTime);

        //组装encodeStr参数
        StringBuffer encodeStr = new StringBuffer(Constant.Business.SPMSCode + "$" + Constant.Business.OperateType);
        encodeStr.append("$" + business.getUserNumber());
        encodeStr.append("$" + business.getSpid());
        encodeStr.append("$" + business.getServiceType());
        encodeStr.append("$" + business.getOperateCode());
        encodeStr.append("$" + business.getFeeType());

        if (business.getFee() != null) {
            encodeStr.append("$" + business.getFee());
        }

        if (StringUtils.isNotEmpty(business.getOrderMethod())) {
            encodeStr.append("$" + business.getOrderMethod());
        }

        param.append("&EncodeStr=" + encodeStr.toString());

        if (StringUtils.isNotEmpty(business.getOrderMsg())) {
            param.append("&Ordermsg=" + business.getOrderMsg());
        }

        if (StringUtils.isNotEmpty(business.getOrderCode())) {
            param.append("&OrderCode=" + business.getOrderCode());
        }

        return param.toString();
    }

    /**
     * 向指定url发送get请求
     * @param url
     * @param param
     * @return
     */
    private JsonData sendGet(String url, String param, Business business) {
        JsonData jsonData = new JsonData();

        String result = "";
        BufferedReader in = null;
        try {
            String urlNameString = url + "?" + param;

            logger.debug("请求url:>>>>>>>>>>>>>>" + urlNameString);

            URL realUrl = new URL(urlNameString);
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 建立实际的连接
            connection.connect();
            // 获取所有响应头字段
            Map<String, List<String>> map = connection.getHeaderFields();
            // 遍历所有的响应头字段
            for (String key : map.keySet()) {
                System.out.println(key + "--->" + map.get(key));
            }
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }

            logger.debug("result--->" + result);
            business.setUrl(urlNameString);
            jsonData.setSuccess(true);
            jsonData.setMsg(result);
            jsonData.setObj(business);
        } catch (Exception e) {
            System.out.println("发送GET请求出现异常！" + e);
            e.printStackTrace();
            jsonData.setSuccess(false);
            jsonData.setMsg(e.getMessage());
        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return jsonData;
    }

}
